package com.huey.utils.fx;

import org.springframework.http.HttpStatus;
import org.springframework.validation.BindException;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.ResponseStatus;

import javax.validation.ValidationException;

/**
 * @author xubo
 * @date 2022/7/12 15:30
 */
@ControllerAdvice(basePackages="com.huey.utils.api")
public class WebExceptionHandler {

    /**
     * validate异常统一处理，前端需要在业务逻辑中处理此异常，返回422
     */
    @ResponseStatus(HttpStatus.UNPROCESSABLE_ENTITY)
    @ExceptionHandler(BindException.class)
    @ResponseBody
    public WebResult handleException(final BindException validationException) {
        WebResult webResult = new WebResult();
        webResult.setCode(String.valueOf(HttpStatus.UNPROCESSABLE_ENTITY.value()));
        int i = validationException.getMessage().lastIndexOf(";");
        webResult.setMessage(validationException.getMessage().substring(i+19,validationException.getMessage().length()-3));
        return webResult;
    }
}
